<template>
	<el-form
		class='page-register'
		ref="form"
		:model="form"
		:rules="rules"
		label-width="0">
		<el-form-item prop="username">
			<el-input
				v-model="form.username"
				@input="changeUsername"
				@blur="validateUsername"
				autocomplete="off"
				placeholder="用户名"
			>
				<i
					v-if="usernameLoading"
					slot="suffix"
					class="el-input__icon el-icon-loading"></i>
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input
				v-model="form.password"
				:show-password="true"
				autocomplete="off"
				type="password"
				placeholder="密码"
			></el-input>
		</el-form-item>
		<el-form-item prop="gender">
			<el-radio-group v-model="form.gender">
				<el-radio :label="MALE">{{GENDER_MAP[MALE]}}</el-radio>
				<el-radio :label="FEMALE">{{GENDER_MAP[FEMALE]}}</el-radio>
			</el-radio-group>
		</el-form-item>
		<el-form-item prop="birthday">
			<el-date-picker
				v-model="form.birthday"
				value-format="yyyy-MM-dd"
				type="date"
				placeholder="生日">
			</el-date-picker>
		</el-form-item>
		<el-form-item prop="email">
			<el-input
				v-model="form.email"
				placeholder="邮箱"></el-input>
		</el-form-item>
		<el-form-item prop="phone">
			<el-input
				v-model="form.phone"
				placeholder="手机号"></el-input>
		</el-form-item>
		<el-form-item prop="provinceCityArea">
			<el-cascader
				v-model="form.provinceCityArea"
				style="width: 220px"
				filterable
				:options="options"
				:props="{ expandTrigger: 'hover' }"
			></el-cascader>
		</el-form-item>
		<el-form-item prop="address">
			<el-input
				v-model="form.address"
				placeholder="地址"></el-input>
		</el-form-item>
		<el-form-item class="register-container">
			<el-button
				type="primary"
				:loading="loading"
				@click="register"
			>
				{{loading ? '正在注册' : '注册'}}
			</el-button>
			<el-link
				href="#/login"
				:underline="false"
				type="primary">账户登录
			</el-link>
		</el-form-item>
	</el-form>
</template>

<script>
  /**
   *
   *
   *
   */
  import * as CONSTANT from '../config/constant'
  import utils from '../utils/index'
  import Validators from "../config/validators";
  import options from "../config/china-division";

  const validator = new Validators()
  export default {
    name: "register",
    data() {
      return {
        ...CONSTANT,
        options: options,
        form: utils.getDefaultRegisterForm(),
        rules: {
          username: [{required: true, validator: validator.validateUsername, trigger: 'change'}],
          password: [{required: true, validator: validator.validatePassword, trigger: 'change'}],
          gender: [{required: true, validator: validator.validateGender, trigger: 'change'}],
          birthday: [{required: true, validator: validator.validateBirthday, trigger: 'change'}],
          email: [{required: true, validator: validator.validateEmail, trigger: 'change'}],
          phone: [{required: true, validator: validator.validatePhone, trigger: 'change'}],
          provinceCityArea: [{required: true, validator: validator.validateProvinceCityArea, trigger: 'change'}],
          address: [{required: true, validator: validator.validateAddress, trigger: 'change'}]
        },
        loading: false,
        usernameLoading: false,
        usernameError: undefined
      }
    },
    watch: {
      'form.provinceCityArea': {
        deep: true,
        immediate: true,
        handler(list) {
          let [province, city, area] = list || []
          this.form.province = province || ''
          this.form.city = city || ''
          this.form.area = area || ''
        }
      },
      usernameError(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.$refs.form.validateField('username')
        }
      }
    },
    mounted() {
      validator.context = this
    },
    methods: {
      changeUsername() {
        this.usernameError = undefined
      },
      validateUsername() {
        const api = '/user/isUsernameValid'
        let username = this.form.username
        this.$cancel(api)
        this.usernameError = undefined
        if (!username) {
          this.usernameLoading = false
          return false
        }
        this.usernameLoading = true
        this.$axios.post(api, {
          username: this.form.username
        }, {
          abort: true
        }).then(({success, message}) => {
            if (!success) {
              this.usernameError = message
            }
          })
          .catch(thrown => {
            this.$message({
              type: 'error',
              message: thrown.message
            })
          })
          .finally(() => {
            this.usernameLoading = false
          })
      },
      register() {
        this.$refs.form.validate(valid => {
          if (!valid) return false
          this.loading = true
	        let params = {
            ...this.form
	        }
          delete params.provinceCityArea
          this.$axios.post('/user/register', params)
            .then(({success, message}) => {
              if (success) {
                this.$notify({
                  type: 'success',
                  title: '账号注册成功'
                })
                this.$router.replace('/user/info')
              } else {
                if (/用户名/.test(message)) {
                  this.usernameError = message
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              }
            })
            .catch(thrown => {
              this.$message({
                type: 'error',
                message: thrown.message
              })
            })
            .finally(() => {
              this.loading = false
            })
        })
      }
    }
  }
</script>

<style lang='less'>
	.page-register {
		.register-container {

			.el-button {
				float: left;
				min-width: 110px;
				flex-shrink: 0;
				flex-grow: 0;
			}

			.el-link {
				float: right;
			}
		}
	}
</style>
